﻿using System.Windows;
using MvvmLight1.ViewModel;
using Microsoft.Win32;
using System;
using System.Windows.Threading;
using System.Windows.Controls.Primitives;
using System.Threading;

namespace MvvmLight1
{
    /// <summary>
    /// This application's main window.
    /// </summary>
    public partial class MainWindow : Window
    {
        DispatcherTimer timer;
        bool isDragging = false;

        /// <summary>
        /// Initializes a new instance of the MainWindow class.
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();    
            Closing += (s, e) => ViewModelLocator.Cleanup();
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(200);
            timer.Tick += new EventHandler(timer_Tick);
        }

        void timer_Tick(object sender, EventArgs e)
        {
            if (!isDragging && MediaEl.Status == PlayerStatus.Play)
            {
                sliderPosition.Value = MediaEl.Position.TotalSeconds;
            }

            if (MediaEl.Status == PlayerStatus.Play)
            {
                var vm = (MainViewModel)DataContext;
                // show banner if needed.
                vm.ProcessBanner(MediaEl.Position.TotalSeconds);
                //ThreadPool.QueueUserWorkItem((Action) => { vm.ProcessBanner(MediaEl.Position.TotalSeconds); });
            }
        }

        private void MediaEL_MediaOpen(object sender, RoutedEventArgs e)
        {
            timer.Stop();
            if (MediaEl.NaturalDuration.HasTimeSpan)
            {
                TimeSpan ts = MediaEl.NaturalDuration.TimeSpan;
                sliderPosition.Maximum = ts.TotalSeconds;
                sliderPosition.SmallChange = 1;
                sliderPosition.LargeChange = Math.Min(10, ts.Seconds / 10);
 
                var vm = (MainViewModel)DataContext;
                // reset the banner time lines
                vm.OrganizeBannersTimeLine(ts.TotalSeconds);
                //ThreadPool.QueueUserWorkItem((Action) => { vm.OrganizeBannersTimeLine(ts.TotalSeconds); });
            }
            timer.Start();
        }

        private void sliderPosition_DragStarted(object sender, DragStartedEventArgs e)
        {
            isDragging = true;
        }

        private void sliderPosition_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            isDragging = false;
            MediaEl.Position = TimeSpan.FromSeconds(sliderPosition.Value);

            var vm = (MainViewModel)DataContext;
            // adjust the curentTimeLine to the Slider Position.
            vm.CalcTimeLine(sliderPosition.Value);
        }
    }
}